<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SQLite数据库浏览器 - 带图表功能</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 1400px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            margin: 20px;
        }
        
        header {
            background: #2575fc;
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
            max-width: 800px;
            margin: 0 auto;
        }
        
        .upload-section {
            padding: 30px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }
        
        .file-input {
            display: none;
        }
        
        .file-label {
            display: inline-block;
            padding: 15px 30px;
            background: #6a11cb;
            color: white;
            border-radius: 50px;
            cursor: pointer;
            font-size: 1.1rem;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(106, 17, 203, 0.3);
        }
        
        .file-label:hover {
            background: #5a0db9;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(106, 17, 203, 0.4);
        }
        
        .file-info {
            margin-top: 15px;
            font-size: 1rem;
            color: #666;
        }
        
        .content-section {
            display: flex;
            flex-direction: row;
            height: 500px;
        }
        
        .tables-panel {
            width: 250px;
            border-right: 1px solid #eee;
            padding: 20px;
            overflow-y: auto;
        }
        
        .tables-panel h2 {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: #2575fc;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        
        .table-list {
            list-style: none;
        }
        
        .table-item {
            padding: 12px 15px;
            margin-bottom: 8px;
            background: #f8f9fa;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .table-item:hover {
            background: #e9ecef;
        }
        
        .table-item.active {
            background: #2575fc;
            color: white;
        }
        
        .data-panel {
            flex: 1;
            padding: 20px;
            overflow: auto;
            display: flex;
            flex-direction: column;
        }
        
        .data-panel h2 {
            font-size: 1.3rem;
            margin-bottom: 15px;
            color: #2575fc;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
            font-size: 0.9rem;
        }
        
        th, td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
            position: sticky;
            top: 0;
        }
        
        tr:hover {
            background-color: #f1f3f5;
        }
        
        .status {
            padding: 20px;
            text-align: center;
            color: #666;
            font-style: italic;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: white;
            margin-top: auto;
        }
        
        .error {
            color: #dc3545;
            background: #f8d7da;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
        }
        
        .sample-db {
            margin-top: 15px;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .sample-db a {
            color: #6a11cb;
            text-decoration: none;
        }
        
        .sample-db a:hover {
            text-decoration: underline;
        }
        
        .chart-controls {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }
        
        .chart-controls select, .chart-controls button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: white;
        }
        
        .chart-controls button {
            background: #6a11cb;
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .chart-controls button:hover {
            background: #5a0db9;
        }
        
        .chart-container {
            flex: 1;
            min-height: 300px;
            margin-top: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            background: white;
        }
        
        @media (max-width: 1024px) {
            .content-section {
                flex-direction: column;
                height: auto;
            }
            
            .tables-panel {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid #eee;
                max-height: 200px;
            }
        }
    </style>
    <!-- 引入Chart.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <div class="container">
        <header>
            <h1>SQLite数据库浏览器 - 带图表功能</h1>
            <p class="description">上传SQLite数据库文件并生成数据图表</p>
        </header>
        
        <div class="upload-section">
            <input type="file" id="db-file" class="file-input" accept=".db,.sqlite,.sqlite3">
            <label for="db-file" class="file-label">选择数据库文件</label>
            <p class="file-info" id="file-info">尚未选择文件</p>
            
            <div class="sample-db">
                <p>没有SQLite数据库文件？<a href="#" id="create-sample">创建示例数据库</a></p>
            </div>
        </div>
        
        <div class="content-section">
            <div class="tables-panel">
                <h2>数据表</h2>
                <ul class="table-list" id="table-list">
                    <li class="table-item">上传数据库后显示表列表</li>
                </ul>
            </div>
            
            <div class="data-panel">
                <h2>数据内容</h2>
                <div id="table-data">请从左侧选择数据表</div>
                
                <div class="chart-controls" id="chart-controls" style="display: none;">
                    <div>
                        <label>X轴列:</label>
                        <select id="x-axis-select"></select>
                    </div>
                    <div>
                        <label>Y轴列:</label>
                        <select id="y-axis-select"></select>
                    </div>
                    <button id="generate-chart">生成折线图</button>
                </div>
                
                <div class="chart-container">
                    <canvas id="data-chart"></canvas>
                </div>
            </div>
        </div>
        
        <div class="status" id="status">
            等待上传数据库文件...
        </div>
    </div>
    
    <div class="footer">
        <p>SQLite数据库浏览器 &copy; 2023 - 带图表功能</p>
    </div>

    <!-- 引入sql.js库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/sql-wasm.js"></script>
    <script>
        // 初始化变量
        let db = null;
        let currentTableData = null;
        let currentColumns = null;
        let dataChart = null;
        
        const fileInput = document.getElementById('db-file');
        const fileInfo = document.getElementById('file-info');
        const tableList = document.getElementById('table-list');
        const tableData = document.getElementById('table-data');
        const status = document.getElementById('status');
        const createSampleBtn = document.getElementById('create-sample');
        const chartControls = document.getElementById('chart-controls');
        const xAxisSelect = document.getElementById('x-axis-select');
        const yAxisSelect = document.getElementById('y-axis-select');
        const generateChartBtn = document.getElementById('generate-chart');
        const dataChartCanvas = document.getElementById('data-chart');
        
        // 加载SQL.js
        status.textContent = '正在加载SQL.js引擎...';
        
        // 配置SQL.js
        const config = {
            locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.8.0/${file}`
        };
        
        // 初始化数据库
        initSqlJs(config).then(function(SQL) {
            status.textContent = 'SQL.js引擎加载完成，请上传数据库文件';
            
            // 文件选择事件处理
            fileInput.addEventListener('change', function(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
                status.textContent = '正在读取数据库...';
                
                const reader = new FileReader();
                reader.onload = function() {
                    try {
                        // 解析数据库文件
                        const Uints = new Uint8Array(reader.result);
                        db = new SQL.Database(Uints);
                        
                        // 显示数据库表
                        displayTables();
                        status.textContent = '数据库加载成功！';
                    } catch (error) {
                        console.error(error);
                        status.textContent = '错误: ' + error.message;
                        tableData.innerHTML = '<div class="error">无法解析数据库文件，请确保是有效的SQLite数据库</div>';
                    }
                };
                reader.onerror = function() {
                    status.textContent = '读取文件时发生错误';
                    tableData.innerHTML = '<div class="error">读取文件时发生错误，请重试</div>';
                };
                reader.readAsArrayBuffer(file);
            });
            
            // 创建示例数据库
            createSampleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                createSampleDatabase(SQL);
            });
            
            // 生成图表按钮事件
            generateChartBtn.addEventListener('click', function() {
                generateChart();
            });
            
        }).catch(function(error) {
            status.textContent = '加载SQL.js失败: ' + error.message;
            console.error(error);
            tableData.innerHTML = '<div class="error">加载SQL.js引擎失败: ' + error.message + '</div>';
        });
        
        // 创建示例数据库
        function createSampleDatabase(SQL) {
            try {
                status.textContent = '正在创建示例数据库...';
                
                // 创建新的内存数据库
                db = new SQL.Database();
                
                // 创建示例表和数据
                db.run(`
                    CREATE TABLE sales (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        month TEXT NOT NULL,
                        revenue REAL NOT NULL,
                        expenses REAL NOT NULL,
                        profit REAL NOT NULL
                    );
                `);
                
                // 插入示例数据
                db.run(`
                    INSERT INTO sales (month, revenue, expenses, profit) VALUES
                    ('一月', 15000, 9000, 6000),
                    ('二月', 18000, 10000, 8000),
                    ('三月', 22000, 12000, 10000),
                    ('四月', 19000, 11000, 8000),
                    ('五月', 25000, 13000, 12000),
                    ('六月', 30000, 15000, 15000),
                    ('七月', 28000, 14000, 14000),
                    ('八月', 32000, 16000, 16000),
                    ('九月', 35000, 18000, 17000),
                    ('十月', 38000, 19000, 19000),
                    ('十一月', 42000, 21000, 21000),
                    ('十二月', 45000, 22000, 23000);
                `);
                
                fileInfo.textContent = '使用示例数据库';
                displayTables();
                status.textContent = '示例数据库创建成功！';
                
            } catch (error) {
                console.error(error);
                status.textContent = '创建示例数据库时出错: ' + error.message;
                tableData.innerHTML = '<div class="error">创建示例数据库时出错: ' + error.message + '</div>';
            }
        }
        
        // 显示数据库中的所有表
        function displayTables() {
            try {
                // 获取所有表名
                const tables = db.exec("SELECT name FROM sqlite_master WHERE type='table'");
                
                if (!tables || tables.length === 0) {
                    tableList.innerHTML = '<li class="table-item">数据库中没有找到表</li>';
                    return;
                }
                
                // 清空表列表
                tableList.innerHTML = '';
                
                // 添加表到列表
                tables[0].values.forEach(tableNameArray => {
                    const tableName = tableNameArray[0];
                    const li = document.createElement('li');
                    li.className = 'table-item';
                    li.textContent = tableName;
                    li.addEventListener('click', function() {
                        // 移除所有active类
                        document.querySelectorAll('.table-item').forEach(item => {
                            item.classList.remove('active');
                        });
                        // 添加active类到当前项
                        li.classList.add('active');
                        // 显示表数据
                        displayTableData(tableName);
                    });
                    tableList.appendChild(li);
                });
                
                // 默认选择第一个表
                if (tables[0].values.length > 0) {
                    const firstTable = tables[0].values[0][0];
                    const firstTableItem = tableList.querySelector('.table-item');
                    if (firstTableItem) {
                        firstTableItem.classList.add('active');
                        displayTableData(firstTable);
                    }
                }
            } catch (error) {
                console.error(error);
                status.textContent = '获取表列表时出错: ' + error.message;
                tableData.innerHTML = '<div class="error">获取表列表时出错: ' + error.message + '</div>';
            }
        }
        
        // 显示表数据
        function displayTableData(tableName) {
            status.textContent = `正在加载表: ${tableName}`;
            
            try {
                // 查询表数据
                const result = db.exec(`SELECT * FROM ${tableName}`);
                
                if (!result || result.length === 0) {
                    tableData.innerHTML = '<p>表中没有数据</p>';
                    status.textContent = `表 "${tableName}" 中没有数据`;
                    chartControls.style.display = 'none';
                    return;
                }
                
                currentColumns = result[0].columns;
                currentTableData = result[0].values;
                
                // 创建表格
                let html = '<table>';
                
                // 表头
                html += '<tr>';
                currentColumns.forEach(col => {
                    html += `<th>${col}</th>`;
                });
                html += '</tr>';
                
                // 表数据
                currentTableData.forEach(row => {
                    html += '<tr>';
                    row.forEach(cell => {
                        // 处理NULL值和长文本
                        let cellContent = cell;
                        if (cell === null) {
                            cellContent = '<i>NULL</i>';
                        } else if (typeof cell === 'string' && cell.length > 50) {
                            cellContent = cell.substring(0, 50) + '...';
                        }
                        html += `<td>${cellContent}</td>`;
                    });
                    html += '</tr>';
                });
                
                html += '</table>';
                tableData.innerHTML = html;
                
                // 显示图表控件
                setupChartControls(currentColumns);
                
                status.textContent = `表 "${tableName}" 已加载，共 ${currentTableData.length} 行数据`;
            } catch (error) {
                console.error(error);
                status.textContent = `错误: ${error.message}`;
                tableData.innerHTML = `<div class="error">无法读取表数据: ${error.message}</div>`;
                chartControls.style.display = 'none';
            }
        }
        
        // 设置图表控件
        function setupChartControls(columns) {
            // 清空现有的选项
            xAxisSelect.innerHTML = '';
            yAxisSelect.innerHTML = '';
            
            // 添加选项
            columns.forEach(column => {
                const xOption = document.createElement('option');
                xOption.value = column;
                xOption.textContent = column;
                xAxisSelect.appendChild(xOption);
                
                const yOption = document.createElement('option');
                yOption.value = column;
                yOption.textContent = column;
                yAxisSelect.appendChild(yOption);
            });
            
            // 默认选择第一个数值列作为Y轴
            const numericColumns = columns.filter((col, index) => {
                // 简单检查是否为数值列
                if (currentTableData && currentTableData.length > 0) {
                    const sampleValue = currentTableData[0][index];
                    return typeof sampleValue === 'number' || !isNaN(parseFloat(sampleValue));
                }
                return false;
            });
            
            if (numericColumns.length > 0) {
                yAxisSelect.value = numericColumns[0];
            }
            
            // 显示图表控件
            chartControls.style.display = 'flex';
            
            // 销毁现有的图表
            if (dataChart) {
                dataChart.destroy();
            }
        }
        
        // 生成图表
        function generateChart() {
            const xAxisColumn = xAxisSelect.value;
            const yAxisColumn = yAxisSelect.value;
            
            if (!xAxisColumn || !yAxisColumn) {
                alert('请选择X轴和Y轴列');
                return;
            }
            
            const xIndex = currentColumns.indexOf(xAxisColumn);
            const yIndex = currentColumns.indexOf(yAxisColumn);
            
            if (xIndex === -1 || yIndex === -1) {
                alert('选择的列不存在');
                return;
            }
            
            // 提取数据
            const labels = [];
            const data = [];
            
            currentTableData.forEach(row => {
                labels.push(row[xIndex]);
                
                // 尝试转换为数字
                const value = parseFloat(row[yIndex]);
                data.push(isNaN(value) ? 0 : value);
            });
            
            // 创建图表
            if (dataChart) {
                dataChart.destroy();
            }
            
            const ctx = dataChartCanvas.getContext('2d');
            dataChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: yAxisColumn,
                        data: data,
                        backgroundColor: 'rgba(106, 17, 203, 0.2)',
                        borderColor: 'rgba(106, 17, 203, 1)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(106, 17, 203, 1)',
                        pointBorderColor: '#fff',
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: 'rgba(106, 17, 203, 1)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: yAxisColumn
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: xAxisColumn
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: `${yAxisColumn} 相对于 ${xAxisColumn} 的折线图`
                        }
                    }
                }
            });
            
            status.textContent = `已生成图表: ${xAxisColumn} 为X轴, ${yAxisColumn} 为Y轴`;
        }
    </script>
</body>
</html>